import json

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

# Create your views here.
# 接口开发
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apitest.models import UserInfo
from apitest.serializers import UserInfoSerializer


def index(request):
    return render(request, 'index.html')


# (andorid.ios)->json(java。python 对象 反序列化) ->json(html ,android ,ios)
# 支持数据接收-》 model->json

def userlist3(request):
    if request.method == "GET":
        query_name = request.GET.get("name")
    elif request.method == "POST":
        if request.content_type == "application/json":
            body = json.loads(request.body.decode())  # 反序列化 json->pyton对象
            query_name = body['name']
        else:
            query_name = request.POST.get("name")
    list = UserInfo.objects.filter(name=query_name)
    json_list = []
    for item in list:
        json_list.append({
            'name': item.name,
            'id': item.id,
        })
    return JsonResponse(json_list, safe=False)


from django.views import View

class UserInfoView(View):

    def get(self, request):
        return HttpResponse('my name is view_class get')

    def post(self, request):
        if request.content_type == 'application/json':
            #参数校验
            body = json.loads(request.body.decode())
            id = body['id']
        else:
            id = request.POST['id']
        queryset = UserInfo.objects.filter(id=id)
        json_lists = []
        for item in queryset:
            json_lists.append({
                'name': item.name,
                'id': item.id,
            })
        return JsonResponse(json_lists, safe=False)

    def delete(self, request):
     return HttpResponse('my name is view_class post')


    def put(self, request):
      return HttpResponse('put')


from rest_framework import viewsets

# crud 都不需要自己写了 有个超级父类 接口开发 model调用全部简化掉
class UserInfoDRFView(ModelViewSet):
    queryset = UserInfo.objects.all()  #数据集
    serializer_class = UserInfoSerializer  #序列号器
    filterset_fields = ('name', 'age') #多条件精准搜索
    search_fields = ('name','age')  # 支持模糊搜索
    ordering_fields = ("age",)  # 排序字段
    #自定义方法 案例
    # @action(methods=['post'], detail=False)
    # def setCase(self, request):
    #     query_name = request.query_params.get('name')
    #     age = request.query_params.get('age')
    #     obj = UserInfo.objects.filter(name=query_name, age=age)
    #     if (obj.exists()):
    #         ser = UserInfoSerializer(obj, many=True)
    #         return Response(ser.data, status=status.HTTP_200_OK)
    #     return Response({}, status=status.HTTP_200_OK)


class UserInfoApiView(APIView):
    def get(self, request):
        queryset = UserInfo.objects.all()
        serializer = UserInfoSerializer(queryset, many=True)
        return JsonResponse(serializer.data, safe=False)